package com.nuanshui.heatedloan.extension.filter;

import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSON;
import com.nuanshui.heatedloan.constant.DubboTransferConstant;
import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.framework.behavior.BehaviorContext;
import com.nuanshui.framework.springContext.SpringContextUtil;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.framework.utils.mongo.MongoManager;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.userinfo.model.SimpleUserInfo;
import com.nuanshui.heatedloan.userinfo.model.User;
import com.nuanshui.heatedloan.userinfo.tool.UserTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StopWatch;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class TraceFilter extends OncePerRequestFilter {

	private Logger log = LoggerFactory.getLogger("access");
	private MongoManager mongoManager;
	private static List<String> filterUrl = Arrays.asList("//statisticsData/saveAndPush","/statisticsData/saveAndPush","/msg/newMsg/status","//msg/newMsg/status");

	@SuppressWarnings("deprecation")
	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		StopWatch stopWatch = new StopWatch();

		mongoManager = SpringContextUtil.getBean("mongoManger");
		StringBuilder sb = new StringBuilder();
		User curUser = getCurrentUser(request);
		UserAgent userAgent = (UserAgent) request.getAttribute(GlobalParam.USER_AGENT);
		String safeToken = userAgent.getSafeToken();
		/*sport.setAccessTime(new Date()); //插入穿件的时间
		sport.setHour(new Date().getHours() + "");
		sport.setIp(request.getRemoteAddr());*/
		if(curUser!=null) {
			LogUtil.init(curUser.getNick().replaceAll("\n", ""),curUser.getId(), safeToken);
			BehaviorContext.removeContext();

			String unique=RpcContext.getContext().getAttachment("unique");

			LogUtil.info(log,"TraceFilter-unique:", unique);

			BehaviorContext.getContext().put(DubboTransferConstant.DUBBO_SERVER_CURRENTUSER,JSON.toJSONString(curUser));//保存当前用户信息
			BehaviorContext.getContext().put(DubboTransferConstant.DUBBO_SERVER_USERID,curUser.getId()); //保存当前用户的ID
		}
		try {
	    	
	    	String userAgentJson=JSON.toJSONString(userAgent);

			BehaviorContext.getContext().put(GlobalParam.USER_AGENT,userAgentJson);
            
		    String openId=(String) request.getHeader(DubboTransferConstant.DUBBO_SERVER_OPENID);
			BehaviorContext.getContext().put(DubboTransferConstant.DUBBO_SERVER_OPENID,openId);
		    
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		    Object principal = auth.getPrincipal();
		    sb.append("TRACE: user【");
	        sb.append("client："+userAgent.getClient()+"-------");
	       /* sport.setClient(userAgent.getClient());
	        stringBuffer.append("version："+userAgent.getVersion()+"------");
	        sport.setVersion(userAgent.getVersion());
	        stringBuffer.append("builder："+userAgent.getBuild()+"------");
	        sport.setBuilder(userAgent.getBuild());
	        stringBuffer.append("deviceToken："+userAgent.getDeviceToken()+"-------");
	        sport.setDeviceToken(userAgent.getDeviceToken());
	        stringBuffer.append("userId："+userAgent.getUserId()+"-------");
	        sport.setUserId(userAgent.getUserId());
	        stringBuffer.append("safe_token"+userAgent.getSafeToken()+"--------");
	        sport.setSafeToken(userAgent.getSafeToken());
	        sport.setRequest(requestURI);
		    if (principal != null && principal instanceof User) {
	            User user = (User)principal;
	            stringBuffer.append("username："+user.getNick()+"】：");
	            sport.setUserName(user.getNick());
	            stringBuffer.append(requestURI);
	           
	        } else {
	        	
	            stringBuffer.append("anonymouse user access】： " + requestURI);        
	        } */
		    if (StringUtils.isNotEmpty(request.getQueryString())) {
	            sb.append("?"+request.getQueryString());
	        }
		    log.info(sb.toString());
		} catch (Exception e) {
			logger.error("获取请求用户信息失败",e);
		}finally {
			
		}
		stopWatch.start();
		try {
			filterChain.doFilter(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
        
        stopWatch.stop();
        sb.append(" 【"+stopWatch.getLastTaskTimeMillis()+"ms】");
        //sport.setRuntime(stopWatch.getLastTaskTimeMillis());
        sb.append("   Params: " + JSON.toJSONString(request.getParameterMap()));
      //  saveAccessLog(sport);   
        MDC.put("consume_time",stopWatch.getLastTaskTimeMillis()+"");
        log.info(sb.toString());
        LogUtil.destory();
	}
	
	/*private void saveAccessLog(final StatisticsPort sport) {
		
		ThreadPoolTaskExecutor  taskExecutor = SpringContextUtil.getBean("taskExecutor");
		String request  =   sport.getRequest();
		String urlLog =  SpringContextUtil.getPropertiestValue("urlLog");
		if(!"true".equals(urlLog)) return;
		if(filterUrl.contains(request)) return;
		taskExecutor.execute(new Runnable() {		
			@Override
			public void run() {
				try {
		        	//将将统计信息插入到mongodb中
		            BasicDBObject dbObj = new BasicDBObject();
		            dbObj.append("ip", JSON.parse(JSON.toJSONString(sport.getIp())));
		            dbObj.append("userId", JSON.parse(JSON.toJSONString(sport.getUserId())));
		            dbObj.append("userName", JSON.parse(JSON.toJSONString(sport.getUserName())));
		            dbObj.append("client", JSON.parse(JSON.toJSONString(sport.getClient())));
		            dbObj.append("version", JSON.parse(JSON.toJSONString(sport.getVersion())));
		            dbObj.append("builder", JSON.parse(JSON.toJSONString(sport.getBuilder())));
		            dbObj.append("deviceToken", JSON.parse(JSON.toJSONString(sport.getDeviceToken())));
		            dbObj.append("safeToken", JSON.parse(JSON.toJSONString(sport.getSafeToken())));
		            dbObj.append("runtime", JSON.parse(JSON.toJSONString(sport.getRuntime())));
		            dbObj.append("request", JSON.parse(JSON.toJSONString(sport.getRequest())));
		            dbObj.append("accessTime", JSON.parse(JSON.toJSONString(sport.getAccessTime())));
		            dbObj.append("hour", JSON.parse(JSON.toJSONString(sport.getHour())));
		            mongoManager.saveAndPush("statisticsPort", dbObj );
				} catch (Exception e) {
				} 
				
			}
		});
		
		
	}*/
	
	//获取用户信息
	private User getCurrentUser(HttpServletRequest request) {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();

		if (auth != null) {
			Object principal = auth.getPrincipal();
			if (principal instanceof User) {
			    User user = (User) principal;
			    if (user != null && !user.isAnonymous() ) {
			        return user;
			    }
			}
		}

		User user = new User();
		user.setNick("未登录用户");
		user.setId("");
		return user;
	}

	
	

}
